import os

import facade
from xjlibrary.our_file_dir import BaseDir, ImageFile

curPath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(TopPath, "download", "shusheng_bh", "download", "cover")
BaseDir.create_dir(sPath)
configfile = BaseDir.get_new_path(curPath, "db.ini")


class DownDetail(object):

    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile, "db", logger=self.logger)
        self.proxy = {"http": "http://192.168.30.176:8034",
                      "https": "http://192.168.30.176:8034"}
        self.BASE_URL = 'http://10.5.23.21:9988'

    def down_cover(self):
        sql = "select bookid,cover from shusheng where cover_stat=0 and stat>0"
        rows = self.mysqlutils.SelectFromDB(sql)
        for bookid, cover in rows:
            cover_path = sPath + '/' + str(bookid)[:2]
            if not os.path.exists(cover_path):
                BaseDir.create_dir(cover_path)
            cover_name = cover_path + '/' + str(bookid) + '.jpg'
            if os.path.exists(cover_name):
                sql = "update shusheng set cover_stat=1 where bookid={}".format(bookid)
                self.mysqlutils.ExeSqlToDB(sql)
                continue
            if not cover:
                continue
            url = self.BASE_URL + cover
            BoolResult, errString, r = facade.BaseRequest(url,
                                                          endstring="",
                                                          proxies=self.proxy)
            if BoolResult:
                ImageFile.img_to_format_jpg(r.content, cover_name)
                sql = 'update shusheng set cover_stat=1 where bookid={}'.format(bookid)
                self.mysqlutils.ExeSqlToDB(sql)
            else:
                if r.text.find("Error 404 Not Found") > -1:
                    sql = 'update shusheng set cover_stat=-1 where bookid={}'.format(bookid)
                    self.mysqlutils.ExeSqlToDB(sql)
                else:
                    print("没有返回值,请注意请求速度")


if __name__ == "__main__":
    down = DownDetail()
    down.down_cover()
